<template>
  <div class="statistics">
    <div class="box-right">
      <base-map :defaultTools="extendedTools" class="base-map" @search="handleSearch" ref="workmap"
        @tool-change="handleToolChange">
        <template #left-menu>
          <custom-tree :data="treeData" @selection-change="handleSelectionChange" />
        </template>
        <template #right-panel>
          <native-group-table :data="indexData"/> 
        </template>
        <template #search-bar>
          <search-results-panel :results="searchResults"
            :visible="showSearchPanel && searchResults.length > 0"
            @close="showSearchPanel = false"
            @item-click="zoomToFeature"/>
        </template>
      </base-map>
      <feature-popup v-if="mapInstance" targetLayerName="数据图层" ref="featurePopup"
            :map="mapInstance"
            :exclude-keys="['geometry', 'id', 'layerType']"
            feature-title="详细信息"
            @feature-click="handleFeatureClick">
            <!-- 自定义内容插槽 -->
            <!-- 修改后的自定义插槽内容 -->
          <template v-slot="{ properties }">
            <div class="custom-popup">
              <!-- 标题区域 -->
              <div class="popup-header">
                <el-tag effect="dark" type="success" size="mini" @click="handlerMarker(properties)">进行标记</el-tag>
                <h3 class="title">{{ properties.name || '未命名要素' }}</h3>
              </div>

              <!-- 属性表格 -->
              <el-descriptions :column="1" class="property-table">
                <el-descriptions-item label="类别">
                  <span class="highlight-text">{{ properties.category}}</span>
                </el-descriptions-item>
                
                <el-descriptions-item label="面积" v-if="properties.area && properties.area.km">
                  <div class="area-display">
                    <span class="area-value">{{ properties.area.km }}</span>
                    <span class="area-unit">平方公里</span>
                    <el-divider direction="vertical" />
                    <span class="area-value">{{ properties.area?.mu }}</span>
                    <span class="area-unit">亩</span>
        
                  </div>
                </el-descriptions-item>
                <!-- 扩展属性 -->
                <el-descriptions-item 
                  v-for="(item,idx) of findAllIndexData(properties.departName)" 
                  :key="idx"
                  :label="item.indexName">
                  <el-tag type="success">{{ item.name }} {{ item.value }}</el-tag>
              </el-descriptions-item>
              </el-descriptions>

              <!-- 空状态提示 -->
              <div v-if="!properties" class="empty-tip">
                <i class="el-icon-warning-outline"></i>
                暂无详细属性信息
              </div>
            </div>
          </template>
        </feature-popup>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Ref } from 'vue-property-decorator';
import BaseMap from "@/components/Map/BaseMap.vue";
import WorkTree from "@/views/region/components/WorkTree.vue";
import CustomTree from '@/components/Map/CustomTree.vue';
import DataParamMenu from '@/views/app/components/DataParamMenu.vue'
import { userGeoJson } from '@/api/investDataCommon';
import { searchIndex } from '@/api/findData';
import { treeSelectAll } from '@/api/indexCategory';
import NativeGroupTable from '@/components/Map/work/NativeGroupTable.vue';
import SearchResultsPanel from '@/components/Map/work/SearchResultsPanel.vue';
import FeaturePopup from '@/components/Map/FeaturePopup.vue';
import _ from 'lodash';
import { Getter } from 'vuex-class';
import {
    getLayerByName,
    findFeaturesInGeometry
} from '@/config/mapFunction';

@Component({
  methods: {},
  components: { WorkTree, BaseMap, DataParamMenu, CustomTree ,NativeGroupTable,SearchResultsPanel,FeaturePopup}

})
export default class workData extends Vue {
  @Getter('departInfo') private departInfo!: any;
  @Ref("workmap") workmap;
  @Ref("featurePopup") featurePopup;
  private featurePropId = '';

  debouncedHandleSearch;
  models: any = {
    searchName: '',
    workId: ''
  }
  mapInstance: any = null;
  
  defaultTools = [
    { name: 'cleanWork', label: '清理工作图层', disabled: false }
  ];

  extendedTools = [
    ...this.defaultTools,
    { name: 'analysis', label: '分析', icon: 'el-icon-eleme', disabled: false }
  ];

  private treeData = [];
  private indexCategoryIds: any = [];
  private indexData:any =[];
  private investData:any;
  private searchResults: Array<{id: number, name: string, category: string}> = [];
  private showSearchPanel: any = false;

  handleToolChange(toolName: string | null) {
    console.log('当前激活工具:', toolName);
    // 根据工具类型执行不同操作
    switch (toolName) {
      case 'drawCircle':
        this.initDrawInteraction();
        break;
      case 'cleanWork':
        this.cleanWorkTool();
        break;
      case 'analysis':
        this.analysisTool();
        break;
      case '1':
        this.clearInteractions();
        break;
    }
  }

  private initDrawInteraction() {
    // 初始化绘图逻辑
    console.log('绘制')
   
  }

  handlerMarker(properties: any) {
    if(properties.marked){
      this.$message.info("该要素已标记过");
      return
    }

    this.workmap.createPointFeature(properties.location, properties.name);
    properties.marked = true;
 
}

  handleFeatureClick(properties) {
      console.log('要素属性:', properties);
      this.featurePropId = properties.id;

  }

  private cleanWorkTool() {
    // 初始化测量逻辑
    console.log('清理工作图层');
    this.workmap.cleanupLayer('工作图层');
  }


  private analysisTool() {
    console.log('分析')
    if(this.indexCategoryIds.length == 0) {
      this.$message.info("请先选择分析指标分类数据");
      return;
    }
    const workSource = getLayerByName(this.workmap,'工作图层')?.getSource();
    if(!workSource) {
      this.$message.info("请先绘制工作图层");
      return;
    }
    const features = workSource.getFeatures();
    if(features.length == 0) {
      this.$message.info("请先绘制范围");
      return;
    }
    const feature = features.find((feature) => feature.get('type') !== 'marker'); 
    console.log('找到图层为',feature)
    const dataSource = getLayerByName(this.workmap,'数据图层')?.getSource();
    const findFeatures = findFeaturesInGeometry(feature.getGeometry(),dataSource);
    if(findFeatures.length == 0) {
      this.$message.info("未找到数据");
      return;
    }
    console.log('找到数据为',findFeatures);
    const ids = findFeatures.map((feature) => feature.get('id').replace('Point',''));

   
    searchIndex({
      ... this.departInfo,
      indexList: this.indexCategoryIds,
      ids:ids
    }).then(res => {
      this.indexData = res.data;
      if(this.indexData && this.indexData.length > 0) {
        this.workmap.openRightPanel();
        this.$store.dispatch('setIndexData',  this.indexData);

      }else{
        this.$message.info("未找到匹配数据");
      }
   
    });

  }

  get matchedIndexData() {
    if (!this.featurePropId) return null;
   
    const rs =  this.findAllIndexData(this.featurePropId);
    return rs;
  }


get findAllIndexData() {
  const data = this.indexData;
  return function(name: string){
    if (!data) return [];
    const matched = data
      ?.flatMap((cat: any) => cat.data || [])
      ?.filter((item: any) => item.departName == name);

      return matched ? matched : [];
  }
}

  private clearInteractions() {
    // 清除所有交互
    console.log('清除所有交互')
  }

  private zoomToFeature(featureId: number) {
    const dataLayer = getLayerByName(this.workmap,'数据图层');

    console.log(dataLayer.geometry)
    const feature = dataLayer?.getSource()
      .getFeatures()
      .find(f => f.get('id') === featureId);

    if (feature) {
      const view = this.workmap.map?.getView();
      const geometry = feature.getGeometry();

      if (geometry) {
        view?.fit(geometry.getExtent(), {
          padding: [100, 100, 100, 100],
          duration: 1000,
          maxZoom: 14
        });
      }
      console.log(geometry.getExtent())

       // 新增坐标计算逻辑
       let popupCoord: number[] = [];
            const geomType = geometry.getType();
            
            if (geomType === 'Point') {
                // 点要素直接获取坐标
                popupCoord = geometry.getCoordinates();
            } else if (geomType === 'Polygon') {
                // 多边形要素计算内部点坐标
                const interiorPoint = geometry.getInteriorPoint();
                popupCoord = interiorPoint.getCoordinates();
            } else {
                // 其他几何类型使用范围中心
                const extent = geometry.getExtent();
                popupCoord = [
                    (extent[0] + extent[2]) / 2,
                    (extent[1] + extent[3]) / 2
                ];
            }
       console.log(this.featurePopup)
       console.log(this.mapInstance)
       this.featurePopup?.showPopup(feature,popupCoord);
    }
}

  handleSearch(searchKeyword) {
    const keyword = searchKeyword.trim();
    if (!keyword) {
      this.$message.warning("请输入搜索关键词");
      return;
    }
    const dataLayer = getLayerByName(this.workmap,'数据图层');
    if (!dataLayer) return;

  // 收集所有要素


  // 执行搜索
    this.searchResults = this.searchGeoJSONFeatures(this.investData,{ name: searchKeyword });

    // 显示结果面板
    this.showSearchPanel = true;
    // 高亮显示结果要素
    //this.workmap.highlightSearchResults(this.searchResults);
 
  }


 searchGeoJSONFeatures(geojson, filters) {
  return geojson.features.filter(feature => {
    return Object.entries(filters).every(([key, value]) => {
      // 支持模糊匹配（如名称包含关键字）
      if (typeof value === "string") {
        return feature.properties[key].toLowerCase().includes(value.toLowerCase());
      }
      // 精确匹配（如 ID 或数字类字段）
      return feature.properties[key] === value;
    });
  });
}
 

  handleSelect(item) {

    const findIds = this.workmap.findFeature();
    if (findIds.length == 0) {
      this.$message.info("在指定区域内没有找到数据");
      return;
    }

    this.$message.success(`在指定区域内找到${findIds.length}条数据`);
 
  }

  private handleSelectionChange(selectedIds: number[]) {
    // 处理选中逻辑
    this.indexCategoryIds = selectedIds;  

  }
  searchAddressHandler(name) {

    if (this.isLatLong(name)) {
      this.workmap.updatePosition(name.split(','))
      return;
    }
    this.workmap.searchFeature(name);

  }
  isLatLong(str) {
    const [lat, long] = str.split(',');
    if (isNaN(lat) || isNaN(long)) {
      return false;
    }
    return true;
  }

  startSearch(event) {
    if (event.target.classList.contains('el-input__icon') && this.models.searchName) {
      console.log('后缀图标被点击');
      this.searchAddressHandler(this.models.searchName);
      // 这里写你的点击逻辑
    }

  }
  created() {
   
    this.debouncedHandleSearch = _.debounce(this.startSearch, 1000);

  }

  mounted() {
  
    setTimeout(() => {
      this.mapInstance = this.workmap.map;
     // this.workmap.addVectorLayer(this.departInfo.vectorId, "行政区划",'default');

      userGeoJson(this.departInfo).then(res => {
        if (res.data.features.length > 0) {
          this.investData = res.data;
         // this.workmap.addObjectLayer(res.data, "数据图层",'green');
        }
      })

      treeSelectAll({}).then(res => {
        this.treeData = this.normalizeTreeData(res.data);
      });
    }, 200)


  }

  private normalizeTreeData(data: any[]) {

    if (!data || data.length === 0) {
      return [];
    }
    return data.map(item => ({
      id: item.id,
      label: item.label,
      level: item.level,
      children: item.children ? this.normalizeTreeData(item.children) : [],
      selected: false,
      expanded: false
    }));
  }


}
</script>
<style lang="scss" scoped>
.statistics {
  display: flex;
  height: 100vh;
  overflow: auto; // 隐藏溢出内容

  .box-left {
    height: auto;
  }

  .box-right {
    flex: 1;
    padding: 0px;
    display: flex;
    flex-direction: column;
    gap: 0px;
    overflow: auto;
  }
}

.boundary-right {
  background-color: #fff;
  position: absolute;
  padding: 10px;
  top: 30px;
  left: 18px;
  z-index: 1000;
}

.boundary-left {
  background-color: #fff;
  opacity: 0.6;
  position: absolute;
  padding: 10px;
  bottom: 0px;
  left: 0px;
  z-index: 1000;
  color: darkgreen;
}

.base-map {
  position: relative;
  height: 100%;

}
</style>
